<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Tagify - mix-mode</title>
        <meta name="description" content="Converts HTML input/textarea into Tags component">
        <meta name="author" content="Yair Even-Or">
        <meta name="viewport" content="width=device-width">
        <link rel="stylesheet" href="../dist/tagify.css">
        <script src="../dist/tagify.js"></script>

        <style>
            body{ font: 16px Arial; }
            form{
                max-width:600px;
            }

            form > section{ margin-bottom: 2em; }

            .tagify+input, .tagify+textarea {
                position: initial !important;
                left: 0 !important;
                transform: none !important;
                width: 100%;
                margin-top: .2em;
                min-height: 11ch;
                background: powderblue;
                font-family: "Fira Code";
            }

            .tagify{
                margin: .2em;
                min-width: 400px;
            }
        </style>
    </head>

    <body>
        <form>
            <button type='button' id='addTagsBtn1'>tags injection with <code>addMixTags(["aaa", "bbb"])</code></button>
            <button type='button' id='addTagsBtn2'>Manual tag injection (in second Tagify)</button>
            <br><br>
            <textarea name='mix1' placeholder="type something">    mixed-mode #example [[example]] with [[{"value":"tags"}]].   </textarea>

            <textarea name='mix2' class='tagify-editor' placeholder="type something">
            [[{"value":200, "text":"  cartman  ", "title":"Eric Cartman", "prefix":"@"}]] and [[{"value":1000, "text":"cartman", "title":"xxx", "prefix":"@", "readonly":true}]] [[kyle]] do not know [[homer simpson]] because:
(new line)
          last tag - [[{"value": "readonly", "readonly":true}]]
</textarea>

        </form>


<script>
document.forms[0].reset();

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

var simpleMixInput = document.querySelector('[name="mix1"]')

var settings = {
    mode: "mix",
    trim: false,
    pattern: /@/,
    validate(data){
        // custom validation - no special characters
        return !/[^a-zA-Z0-9 ]/.test(data.value)
    },
    dropdown: {
        enabled: 0,
        position: "text"
    },

    a11y: {
        focusableTags: true
    },

    whitelist: [
        {id: 100, value: "kenny", title: "Kenny McCormick"},
        {id: 101, value: "cartman", title: "Eric Cartman"},
        {id: 102, value: "kyle", title: "Kyle Broflovski"},
        {id: 103, value: "token", title: "Token Black"},
        {id: 104, value: "jimmy", title: "Jimmy Valmer"},
        {id: 105, value: "butters", title: "Butters Stotch"},
        {id: 106, value: "stan", title: "Stan Marsh"},
        {id: 107, value: "randy", title: "Randy Marsh"},
        {id: 108, value: "Mr. Garrison", title: "POTUS"},
        {id: 109, value: "Mr. Mackey", title: "M'Kay"}
    ],
    originalInputValueFormat: tagData => tagData.value
}

var simpleMixTagify = new Tagify(simpleMixInput, settings);
//   simpleMixTagify.on('keydown', e => console.log(e.detail))
simpleMixTagify.on('input', console.log )
simpleMixTagify.on('focus', (e) => console.log('focus', e) )
simpleMixTagify.on('blur', (e) => console.log('blur', e) )
</script>



<script>
    /////////////////////////////////////////////////
    // DEMO 2

    var whitelist_1 = [
        {
            value: 100,
            text : 'kenny',
            title : 'Kenny McCormick'
        },
        {
            value: 200,
            text : 'cartman',
            title : 'Eric Cartman'
        },
        {
            value: 300,
            text : 'kyle',
            title : 'Kyle Broflovski'
        },
        {
            value: 400,
            text : 'token',
            title : 'Token Black'
        },
        {
            value: 500,
            text : 'jimmy',
            title : 'Jimmy Valmer'
        },
        {
            value: 600,
            text : 'butters',
            title : 'Butters Stotch'
        },
        {
            value: 700,
            text : 'stan',
            title : 'Stan Marsh'
        },
        {
            value: 800,
            text : 'randy',
            title : 'Randy Marsh'
        },
        {
            value: 900,
            text : 'Mr. Garrison',
            title : 'POTUS'
        },
        {
            value: 1000,
            text : 'Mr. Mackey',
            title : "M'Kay"
        }
    ]

var whitelist_2 = ['Homer simpson', 'Marge simpson', 'Bart', 'Lisa', 'Maggie', 'Mr. Burns', 'Ned', 'Milhouse', 'Moe'];

var input = document.querySelector('[name=mix2]'),
    // init Tagify script on the above inputs
    tagify = new Tagify(input, {
        tagTextProp      : 'text',
        enforceWhitelist : true, // <-- see below post-init change
        mode             : 'mix',  // <--  Enable mixed-content
        pattern          : /@|#/,  // <--  Tag words which start with @ or # (can be a String instead of Regex)
        duplicates       : false,
        whitelist        : whitelist_1.concat(whitelist_2),   // <--  Set the initial whitelist, which will dynamically changed as you type (see "input" event below)
        dropdown   : {
            enabled : 1,
            maxItems: 20,
            position: 'text',
            highlightFirst: true,
            mapValueTo: 'text'
        },
        callbacks        : {
            add    : e=>console.log("ADD: ", e.detail),  // callback when adding a tag
            remove : e=>console.log("REMOVE: ", e.detail)   // callback when removing a tag
        }
    })

    // POST-INIT change:
    tagify.settings.enforceWhitelist = false

    // A good place to pull server suggestion list according to the prefix/value
    tagify.on('input', async function(e){
        var prefix = e.detail.prefix,
            newWhitelist;

        // tagify.settings.whitelist.length = 0;
        // await delay(1500)

        if( prefix ){
            if( prefix == '@' )
                newWhitelist = whitelist_1
            if( prefix == '#' )
                newWhitelist = whitelist_2

            if( newWhitelist ){
                tagify.settings.whitelist.length = 0;
                tagify.settings.whitelist.push(...newWhitelist)
            }

            if( e.detail.value.length >= tagify.settings.dropdown.enabled )
                tagify.dropdown.show(e.detail.value);
        }

        // console.log('mix-mode "input" event value: ', e.detail, e.detail.tagify.value)
    })

    tagify.on('keydown', function(e){

    })

    addTagsBtn1.addEventListener('click', ()=> {
        const insertedNode = tagify.addMixTags(['aaa', 'bbb'])
    })

    addTagsBtn2.addEventListener('click', ()=> {
        var tagElm = tagify.createTagElem({ value:"my tag" })
        tagify.injectAtCaret(tagElm)
        // A timeout is needed until the node is Acutally in the DOM and focus has been applied
        var elm = tagify.insertAfterTag(tagElm)
        setTimeout(() => {
            tagify.placeCaretAfterNode(elm)
        });
    })

    // window.addEventListener("dblclick", insertTag)
    // function insertTag() {
    //     tagify.addTags("xxx");
    //     tagify.DOM.input.focus();
    // }
</script>
</body>
</html>